package com.iwop.moto.controller;

import com.alibaba.fastjson.JSON;
import com.iwop.moto.auth.LoginAuth;
import com.iwop.moto.cache.RedisUtil;
import com.iwop.moto.comm.ConponConstant;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.model.*;
import com.iwop.moto.service.*;
import com.iwop.moto.utils.PushNoticeUtil;
import com.iwop.moto.utils.api.YunXin.YunXinUtils;
import com.iwop.moto.utils.http.SessionUtils;
import com.iwop.moto.utils.securityUtils.Des3;
import com.iwop.moto.utils.stringUtil.DateUtils;
import com.iwop.moto.utils.stringUtil.ObjectId;
import com.iwop.moto.utils.stringUtil.SequenceUtil;
import com.iwop.moto.utils.stringUtil.StringUtils;
import com.opslab.util.DateUtil;
import com.wordnik.swagger.annotations.ApiParam;
import jxl.write.WriteException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Title: UserController<br>
 * Description: 用户<br>
 * Create DateTime: 2016/12/27 14:37<br>
 *
 * @author chenzhongqiang
 */

@Controller
public class UserController extends BaseController {
    @Autowired
    private SPayPassCodeService   payPassCodeService;
    @Autowired
    private UserService           userService;
    @Autowired
    private SMSService            sMSService;
    @Autowired
    private PromotionService      promotionService;
    @Autowired
    private StoreService          storeService;
    @Autowired
    private BUserService          bUserService;
    @Autowired
    private YunxinService         yunxinService;
    @Autowired
    private FCouponService        fCouponService;
    @Autowired
    private FOrderServiceService  fOrderServiceService;
    @Autowired
    private FErrorLogService      fErrorLogService;
    @Autowired
    private MOrderPurchaseService mOrderPurchaseService;

    @Autowired
    private MCouponService mCouponService;

    @Autowired
    private MPaymentService mPaymentService;

    @Autowired
    private MBankListService mBankListService;

    @Autowired
    private StoreServieService storeServieService;

    @Autowired
    private MGoodsService mgoodsService;

    @Autowired
    private FOrderServiceService orderServiceService;
    @Autowired
    private MGPOrderService      mgpOrderService;
    @Autowired
    FUserFreezeService fUserFreezeService;

    Logger logger = Logger.getLogger(UserController.class);



    /**
     * @模块: APP - 用户登录
     * @作者: huyuanguang create ver 1.0
     * @说明: 根据【用户名/密码/用户类型】进行登录
     * @版本: ver 1.1 by liuwb update
     * 1.新增 userType 用户类型 [1:维修店][5:服务商]
     * @参数: tel 手机号
     * @参数: pwd 密码 (MD5密文)
     * @参数: ctype 用户类型
     */
    @RequestMapping("/api/user_login")
    @ResponseBody
    public ResultModel login(HttpServletRequest request) {
        Jedis jedis = RedisUtil.getJedis();
        ResultModel resultModel = new ResultModel();
        String tel = request.getParameter("tel");
        String pwd = request.getParameter("pwd");
        String type = request.getParameter("ctype");
        String phoneInfo = request.getParameter("phoneInfo");
        //String userType=request.getParameter("userType");

//        String phoneblacklist = PhoneBlacklist.PHONEBLACKLIST;
//        String key = "backphone:"+tel;
//        if (jedis.get(key) != null) {
//            jedis.expire(key, 10);
//            resultModel.setCode(0);
//            resultModel.setMem(ErrCode.PHONEBLACKLIST_LOGIN_ERROR);
//            if (jedis != null) {
//                jedis.close();
//            }
//            return resultModel;
//        }
//        List<FUserFreeze> fUserFreezes = fUserFreezeService.listUserFreeze();
//        for (FUserFreeze fUserFreeze : fUserFreezes) {
//            if (fUserFreeze.getPhone().equals(tel)) {
//                jedis.set(key, tel);
//                jedis.expire(key, 1000);
//                resultModel.setCode(0);
//                resultModel.setMem(ErrCode.PHONEBLACKLIST_LOGIN_ERROR);
//                if (jedis != null) {
//                    jedis.close();
//                }
//                return resultModel;
//            }
//        }
//
//        String[] split = phoneblacklist.split(",");
//        for (int i = 0; i < split.length; i++) {
//            if (tel.equals(split[i])) {
//                resultModel.setCode(0);
//                resultModel.setMem(ErrCode.PHONEBLACKLIST_LOGIN_ERROR);
//                return resultModel;
//            }
//        }
        if (jedis != null) {
            jedis.close();
        }
        if (StringUtils.isEmpty(tel) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(type)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return resultModel;
        }
        User user = new User();
        user.setTel(tel);
        // user.setPwd(pwd);
        try {
            user.setUserType(type);
            user = userService.login(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user == null || StringUtils.isEmpty(user.getSid())) {//用户不存在
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_NOEXIST);
            return resultModel;
        } else if (StringUtils.isEmpty(user.getPwd())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_USERPWDERROR);
            return resultModel;
        } else if (!user.getPwd().equals(pwd)) {//密码不一 致的
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_USERORPWD);
            return resultModel;
        }
//        } else if (user.getUserStatus()==1) {
//            resultModel.setCode(0);
//            resultModel.setMem(ErrCode.USER_ERROR_NOEXIST);
//            return resultModel;
//        }
        SuperRecordModel store = new SuperRecordModel();
        store.put("user_id", user.getSid());
        store = storeService.findStoreByUserId(store);
        SuperRecordModel srmModel = new SuperRecordModel();
        if (store != null) {
            srmModel.put("store_id", store.getString("sid"));
            srmModel.put("address", store.getString("address"));
            srmModel.put("log", store.getString("log"));
            srmModel.put("lat", store.getString("lat"));
            srmModel.put("tel1", store.getString("tel1"));
            srmModel.put("storename", store.getString("storename"));
            srmModel.put("storepath", store.getString("storepath"));
            srmModel.put("click_flag", store.getString("click_flag"));
        }
        SuperRecordModel superReco = yunxinService.getIMUserInfo(user.getSid());
        if (superReco != null && superReco.size() > 0) {
            srmModel.put("login_token", superReco.getString("im_token"));
        }

        if (StringUtils.isNotEmpty(user.getPaypwd())) {
            user.setWhetherPayPwd(true);
        } else {
            user.setWhetherPayPwd(false);
        }
        user.setSrmModel(srmModel);
        resultModel.setData(JSON.toJSONString(user));
        setKeyValueToSession(user.getSid(), user); /** 存入 Redis 缓存中 **/
        //判断是否多台设备登录
        String deviceId = user.getDeviceId();
        String device_id = request.getParameter("device_id");
        if (!StringUtils.isEmpty(device_id)) {
            if (deviceId != null && (!deviceId.equals(device_id))) {
                if (type.equals("1")) {
                    PushNoticeUtil.sendPersonNoticeMessage("您的账号在其他设备登录", "store", device_id, user.getSid());
                } else {
                    PushNoticeUtil.sendPersonNoticeMessage("您的账号在其他设备登录", "user", device_id, user.getSid());
                }
                user.setDeviceId(device_id);
                userService.updateUserByDeviceId(user);
            }
            if (deviceId == null) {
                user.setDeviceId(device_id);
                userService.updateUserByDeviceId(user);
            }
        }
        return resultModel;
    }

    /**
     * 验证码登录
     */
    @RequestMapping("/api/sms_login")
    @ResponseBody
    public ResultModel smsLogin(HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String code = request.getParameter("code");
        String tel = request.getParameter("tel");
        String type = request.getParameter("ctype");
        //String userType=request.getParameter("userType");
        if (StringUtils.isEmpty(tel) || StringUtils.isEmpty(type)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return resultModel;
        }
        SMS sms = new SMS();
        sms.setTel(tel);
        sms = sMSService.findByTelOrId(sms);
        if (sms == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        } else if (sms.getStatus().equals("1")) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS_USED);
            return resultModel;
        } else if (false == sms.getContent().equals(code)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        }
        User user = new User();
        user.setTel(tel);
        user.setUserType(type);
        user = userService.login(user);
        if (user == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_NOEXIST);
            return resultModel;
        }
        SuperRecordModel store = new SuperRecordModel();
        store.put("user_id", user.getSid());
        store = storeService.findStoreByUserId(store);
        SuperRecordModel srmModel = new SuperRecordModel();
        if (store != null) {
            srmModel.put("store_id", store.getString("sid"));
            srmModel.put("address", store.getString("address"));
            srmModel.put("log", store.getString("log"));
            srmModel.put("storename", store.getString("storename"));
            srmModel.put("tel1", store.getString("tel1"));
            srmModel.put("storepath", store.getString("storepath"));
            srmModel.put("lat", store.getString("lat"));
            srmModel.put("click_flag", store.getString("click_flag"));
        }
        SuperRecordModel superReco = yunxinService.getIMUserInfo(user.getSid());
        if (superReco != null && superReco.size() > 0) {
            srmModel.put("login_token", superReco.getString("im_token"));
        } else {
            srmModel.put("login_token", "");
        }
        user.setSrmModel(srmModel);
        resultModel.setData(JSON.toJSONString(user));
        setKeyValueToSession(user.getSid(), user); /** 存入 Redis 缓存中 **/
        //判断是否多台设备登录
        String deviceId = user.getDeviceId();
        String device_id = request.getParameter("device_id");
        if (!StringUtils.isEmpty(device_id)) {
            if (deviceId != null && !deviceId.equals(device_id)) {
                if (type.equals("1")) {
                    PushNoticeUtil.sendPersonNoticeMessage("您的账号在其他设备登录", "store", device_id, user.getSid());
                } else {
                    PushNoticeUtil.sendPersonNoticeMessage("您的账号在其他设备登录", "user", device_id, user.getSid());
                }
                user.setDeviceId(device_id);
            }
            if (deviceId == null) {
                user.setDeviceId(device_id);
                userService.updateUserByDeviceId(user);
            }
        }
        return resultModel;
    }

    /**
     * @模块: APP - 注册
     * @作者: huyuanguang create ver 1.0
     * @说明: 根据[手机号/验证码/昵称(选填)]进行快速注册
     * @版本: ver 1.1 by liuwb 2016-09-05 update
     * 1.新增用户注册生成推广码
     * 2.新增业务逻辑:用户注册填写其他人推广码建立分销关系
     * @参数: username 用户名
     * @参数: ctype 用户类型[1:维修店][2:供应商][5:服务商][]
     * @参数: tel 手机号
     * @参数: code 验证码
     * @参数: pwd 密码(MD5加密后)
     * @参数: surepwd 确认密码(MD5加密后)
     * @参数: nickname 昵称
     * @参数: promotionCode 推广码(选填)
     */
    @RequestMapping("/api/user_register")
    @ResponseBody
    public ResultModel register(HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        try {
            String username = request.getParameter("username");
            String tel = request.getParameter("tel");
            String code = request.getParameter("code");
            String pwd = request.getParameter("pwd");
            String surepwd = request.getParameter("surepwd");
            String type = request.getParameter("ctype");
            String nickname = request.getParameter("nickname");
            if (StringUtils.isEmpty(username) || StringUtils.isEmpty(tel) || StringUtils.isEmpty(code)
                    || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(surepwd) || StringUtils.isEmpty(type)) {
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.ERROR_PARAMETER);
                return resultModel;
            }
            if (!StringUtils.isMobile(tel)) {
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.ERROR_TEL_FORMAT);
                return resultModel;
            }
            if (!pwd.equals(surepwd)) {
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_ERROR_PWS);
                return resultModel;
            }
            SMS sms = new SMS();
            sms.setTel(tel);
            sms = sMSService.findByTelOrId(sms);
            if (sms == null) {
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.ERROR_SMS);
                return resultModel;
            } else if (sms.getStatus().equals("1")) {
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.ERROR_SMS_USED);
                return resultModel;
            } else if (false == sms.getContent().equals(code)) {
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.ERROR_SMS);
                return resultModel;
            }
            User user = new User();
            user.setUsername(username);//用户名
            user.setUserType(type);//用户类型
            User ckUser = userService.findUserByParam(user);//
            if (ckUser != null) {//用户已经存在
                resultModel.setCode(0);
                resultModel.setMem(ErrCode.USER_ERROR_ISEXIST);
                return resultModel;
            }
            user.setSid(ObjectId.userUUID());
            user.setTel(tel);
            user.setPwd(pwd);
//            user.setPaypwd(pwd);
            user.setLevel(0);
            user.setAddbanktime(new Date());
            user.setNickname(nickname == null ? user.getTel() : nickname);
            user.setPromotionCode(StringUtils.getPromotionCode(type, tel));//生成八位推广
            if (type != null && "1".equals(type)) {
                user.setAuditFlag(null);
            } else {
                user.setAuditFlag("0");
            }
            user.setAuditTime(new Date());
            user.setCreateTime(new Date());
            // ChatUtil.addChatUser(user.getSid(),user.getPwd(),user.getNickname());
            String promotionCode = request.getParameter("promotionCode");
            if (StringUtils.isEmpty(promotionCode)) {
                user.setNewUser("old");
            } else {
                user.setNewUser("new");
            }
            userService.register(user);
            SuperRecordModel prUser = new SuperRecordModel();
            if (!"".equals(promotionCode)) {
                prUser = userService.findUserByPromotionCode(promotionCode.toUpperCase());
            }
            if (prUser != null) {// 并且选择推荐服务商
                SuperRecordModel promotionSrm = new SuperRecordModel();
                promotionSrm.put("sid", ObjectId.userUUID());
                String sid = prUser.getString("sid");
                if (StringUtils.isEmpty(sid)) {
                    FErrorLog errorLog = new FErrorLog();
                    errorLog.setErrContent(JSON.toJSONString(prUser));
                    errorLog.setErrName("推荐码错误");
                    errorLog.setErrTime(new Date());
                    errorLog.setSid(ObjectId.UUID());
                    fErrorLogService.insert(errorLog);
                }
                promotionSrm.put("host_user", sid);
                promotionSrm.put("promotion_code", promotionCode);
                promotionSrm.put("from_user", user.getSid());
                promotionSrm.put("status_flag", "1");
                promotionSrm.put("status_time", new Date());
                promotionService.insertPromotion(promotionSrm);
                String flag = "new";
                SessionUtils.setKeyValueString(user.getSid() + "_new", flag);
            } else {
                String flag = "old";
                SessionUtils.setKeyValueString(user.getSid() + "_new", flag);
            }
            //修改手机短信使用状态
            sms.setStatus("1");
            sMSService.save(sms);

            //添加云信用户，好友
            boolean imUser = createIMUser(user);
            //addFriend(user.getSid());
            if (!imUser) {
                logger.error("添加云信用户错误，用户id：" + user.getSid());
            }

            //添加抵用券newUser 新用户注册 赠送 5块钱和100块钱
            this.initCoupon(user);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultModel;
    }

    /**
     * 初始化优惠券
     *
     * @param user
     */
    private void initCoupon(User user) throws ParseException {
        SuperRecordModel srms = new SuperRecordModel();
        if (user.getUserType().equals("1")) {
            srms.put("coupon_type", "newStore");
        } else {
            srms.put("coupon_type", "newUser");
        }
        List<SuperRecordModel> couponByTypes = null;
        try {
            couponByTypes = fCouponService.getCouponByType(srms);
        } catch (Exception e) {
            logger.error("查找优惠券样本出错");
            e.printStackTrace();
        }
        if (!couponByTypes.isEmpty()) {
            for (SuperRecordModel couponByType : couponByTypes) {
                Integer provideNum = Integer.parseInt(String.valueOf(couponByType.get("provide_num")));
                if (provideNum > 0) {
                    SuperRecordModel srm = new SuperRecordModel();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss");
                    Date endTime = format.parse(couponByType.get("end_time").toString());
                    if (endTime.getTime() > new Date().getTime()) {
                        //发放用户抵用券
                        srm.put("sid", ObjectId.UUID());
                        srm.put("user_id", user.getSid());
                        srm.put("coupon_id", couponByType == null ? null : couponByType.getString("sid"));
                        srm.put("withdrawals", "0");
                        srm.put("status_flag", "1");
                        srm.put("start_time", new Date());
                        srm.put("end_time", DateUtils.addDay(new Date(), 30));
                        srm.put("coupon_type", user.getUserType().equals("1") ? ConponConstant.NEWSTORE : ConponConstant.NEWUSER);
                        srm.put("c_time", new Date());
                        int seccess = fCouponService.insertUserCoupon(srm);
                        //更新抵用券发放数量
                        SuperRecordModel srm2 = new SuperRecordModel();
                        srm2.put("provide_num", provideNum - 1);
                        srm2.put("sid", couponByType == null ? null : couponByType.getString("sid"));
                        fCouponService.modifyCouponProvideNum(srm2);
                        if (srms.get("coupon_type").equals("newStore")) {
                            logger.info("新注册维修端【" + user.getNickname() + "】注册获得抵用券" + couponByType.get("money") + "元");
                        } else {
                            logger.info("新注册用户【" + user.getNickname() + "】注册获得抵用券" + couponByType.get("money") + "元");
                        }
                    }
                }
            }
        }
    }

    /**
     * 同步云信用户
     */
    @RequestMapping("/api/synchro/im")
    @ResponseBody
    public ResultModel synchroImUser(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        List<User> srm = userService.findUserAll();
        if (srm != null && srm.size() > 0) {
            for (User user : srm) {
                user.setImgpath(tempContextUrl + user.getImgpath());
                boolean imUser = createIMUser(user);
                addFriend(user.getSid());
                if (!imUser) {
                    logger.error("添加云信用户错误，用户id：" + user.getSid());
                }
            }
        }
        return getSucceed(ErrCode.SUCCEED);
    }

    /**
     * 创建IM用户
     */
    private boolean createIMUser(User user) {
        try {
            String token = SequenceUtil.Serial("S");
            String result = YunXinUtils.addIMUser(user.getSid(), user.getNickname(), user.getImgpath(), token);
            Map parse = (Map) JSON.parse(result);
            int code = (int) parse.get("code");
            if (code == 200) {
                SuperRecordModel srm = new SuperRecordModel();
                srm.put("im_accid", user.getSid());
                srm.put("im_name", user.getNickname());
                srm.put("im_icon", user.getImgpath());
                srm.put("im_token", token);
                yunxinService.insertIM(srm);
                return true;
            } else {
                logger.error("云信注册返回错误结果：" + result);
                logger.error("云信注册时间：" + new Date());
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 云信添加好友
     */
    public void addFriend(String accid) {
        SuperRecordModel model = new SuperRecordModel();
        model.put("Area", "Area");
        model.put("dataValue", "KF");
        List<SuperRecordModel> srm = bUserService.getServiceBUser(model);
        if (srm != null && srm.size() > 0) {
            for (SuperRecordModel SRModel : srm) {
                YunXinUtils.addFriend(accid, SRModel.getString("sid"));
            }
        }
    }

    /***
     * 查找用户
     * username tel code  pwd surepwd type
     * APP登录
     *
     * @param request
     * @return
     */
    @LoginAuth(isval = true)
    @RequestMapping("/api/user_findUser")
    @ResponseBody
    public ResultModel findUser(HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String sid = request.getParameter("sid");
        String tel = request.getParameter("tel");
        String username = request.getParameter("username");
        if (false == (StringUtils.isEmpty(sid) || StringUtils.isEmpty(tel) || StringUtils.isEmpty(username))) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return resultModel;
        }
        User user = new User();
        user.setSid(sid);
        user.setTel(tel);
        user.setUsername(username);
        user = userService.findUserByUser(user);
        if (user == null || StringUtils.isEmpty(user.getSid())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_ISEXIST);
            return resultModel;
        }
        resultModel.setData(JSON.toJSONString(user));
        return resultModel;
    }

    /****
     * @功能: APP - 忘记密码
     * @apiNote 通过手机号获取验证码重置密码
     * @param tel 手机号
     * @param code 验证码
     * @param pwd 密码
     * @param surepwd 确定密码
     * @param ctype 客户端类型 [1:维修店][2:供应商][5:服务商][普通用户:popular]
     */
    @RequestMapping("/api/user_updatepwd")
    @ResponseBody
    public ResultModel updatepwd(
            @ApiParam(name = "tel", value = "手机号")
            @RequestParam(value = "tel") String tel,
            @ApiParam(name = "code", value = "验证码")
            @RequestParam(value = "code") String code,
            @ApiParam(name = "pwd", value = "密码")
            @RequestParam(value = "pwd") String pwd,
            @ApiParam(name = "ctype", value = "客户端类型[1:维修店][2:供应商][5:服务商][普通用户:popular]")
            @RequestParam(value = "ctype") String type,
            @ApiParam(name = "surepwd", value = "确定密码")
            @RequestParam(value = "surepwd") String surepwd,
            HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        if (StringUtils.isEmpty(tel) || StringUtils.isEmpty(code) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(surepwd)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return resultModel;
        }
        if (!StringUtils.isMobile(tel)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_TEL_FORMAT);
            return resultModel;
        }
        if (!pwd.equals(surepwd)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_PWS);
            return resultModel;
        }
        SMS sms = new SMS();
        sms.setTel(tel);
        sms = sMSService.findByTelOrId(sms);
        if (sms == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        } else if (!sms.getContent().equals(code)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        } else if (sms.getStatus().equals("1")) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS_USED);
            return resultModel;
        }
        if (StringUtils.isEmpty(type)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SYSTEM);
            return resultModel;
        }
        User user = new User();
        user.setTel(tel);
        user.setUserType(type);
        user = userService.findUserByParam(user);
        if (user == null || StringUtils.isEmpty(user.getSid())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_ISEXIST);
            return resultModel;
        }
        user.setPwd(pwd);
        user = userService.save(user);
        if (user == null || StringUtils.isEmpty(user.getSid())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_NOEXIST);
            return resultModel;
        }
        //修改手机短信使用状态
        sms.setStatus("1");
        sMSService.save(sms);
        return resultModel;
    }

    /****
     * @功能: 修改用户手机号
     * @作者: huyuangui create ver 1.0
     * @说明: 手机号三个月只能更换一次
     * @参数: session_id 主键
     * @参数: tel 手机号
     * @参数: code 验证码
     */
    @RequestMapping("/api/user_changeTel")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel changeTel(HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String user_id = request.getParameter("session_id");
        String tel = request.getParameter("tel");
        String code = request.getParameter("code");
        String user_type = request.getParameter("user_type");
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(tel) || StringUtils.isEmpty(code)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_TEL_ISNOTNULL);
            return resultModel;
        }
        if (!StringUtils.isMobile(tel)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_TEL_FORMAT);
            return resultModel;
        }
        SMS sms = new SMS();
        sms.setTel(tel);
        sms = sMSService.findByTelOrId(sms);
        if (sms == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        } else if (sms.getStatus().equals("1")) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS_USED);
            return resultModel;
        } else if (false == sms.getContent().equals(code)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        }
        User user = new User();
        user.setSid(user_id);
        user = userService.findUserByUser(user);
        if (user == null && StringUtils.isEmpty(user.getSid())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_TEL_ISNOTNULL);
            return resultModel;
        }
        //判断手机号码是否被使用过
        User user1 = new User();
        user1.setTel(tel);
        //       user1.setSid(user_id);
        user1.setUserType(user_type);
        User userByUser = userService.findUserByParam(user1);
        if (userByUser != null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_TELEXST);
            return resultModel;
        }
        //判断手机号码是否3个月内修改
        if (user.getUpdateTelTime() != null && user.getUpdateTelTime().compareTo(DateUtils.DateToString(DateUtils.addMonth(new Date(), -3), "yyyy-MM-dd HH:mm:ss")) > 0) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_CHANGEONE);
            return resultModel;
        }
        String promotionCode = StringUtils.getPromotionCode(user_type, tel);
        user.setUpdateTelTime("update");
        user.setTel(tel);
        user.setUsername(tel);
        user.setPromotionCode(promotionCode);
        user = userService.save(user);
        if (user == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_SAVE);
            return resultModel;
        }
        sms.setStatus("1");
        sMSService.save(sms);
        return resultModel;
    }


    /**
     * 原手机号码带验证码验证
     *
     * @param session_id 用户id
     * @param tel        原手机号码
     * @param code       验证码
     * @return
     */
    @RequestMapping("/api/changeUserTel")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel changeUserTel(HttpServletRequest request) {
        String user_id = request.getParameter("session_id");
        String tel = request.getParameter("tel");
        String code = request.getParameter("code");
        String user_type = request.getParameter("user_type");
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(tel) || StringUtils.isEmpty(code)) {
            return getErr(ErrCode.ERROR_TEL_ISNOTNULL);
        }
        if (!StringUtils.isMobile(tel)) {
            return getErr(ErrCode.ERROR_TEL_FORMAT);
        }
        User user = new User();
        user.setSid(user_id);
        user.setUserType(user_type);
        user = userService.findUserByParam(user);

        SMS sms = new SMS();
        sms.setTel(tel);
        sms = sMSService.findByTelOrId(sms);
        if (sms == null) {
            return getErr(ErrCode.ERROR_SMS);
        } else if (sms.getStatus().equals("1")) {
            return getErr(ErrCode.ERROR_SMS_USED);
        } else if (false == sms.getContent().equals(code)) {
            return getErr(ErrCode.ERROR_SMS);
        } else if (false == user.getTel().equals(tel)) {
            return getErr(ErrCode.ERROR_TEL_NORIGHT);
        }
        sms.setStatus("1");
        sMSService.save(sms);
        return getSucceed(ErrCode.SUCCEED);
    }

    /**
     * 验证并修改新手机 带验证码
     *
     * @param session_id 用户id
     * @param tel        新手机号码
     * @param code       验证码
     * @param type       客户端类型
     * @return
     */


    @RequestMapping("/api/chackNewTel")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel chackNewTel(HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String user_id = request.getParameter("session_id");
        String tel = request.getParameter("tel");
        String code = request.getParameter("code");
        String user_type = request.getParameter("user_type");

        SMS sms = new SMS();
        sms.setTel(tel);
        sms = sMSService.findByTelOrId(sms);
        if (sms == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        } else if (sms.getStatus().equals("1")) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS_USED);
            return resultModel;
        } else if (false == sms.getContent().equals(code)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_SMS);
            return resultModel;
        }
        User user = new User();
        user.setSid(user_id);
        user.setUserType(user_type);
        user = userService.findUserByUser(user);
        if (user == null || StringUtils.isEmpty(user.getSid())) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_TEL_ISNOTNULL);
            return resultModel;
        }
        //判断手机号码是否被使用过
        User user1 = new User();
        user1.setTel(tel);
//        user1.setSid(user_id);
        user1.setUserType(user_type);
        User userByUser = userService.findUserByParam(user1);
        if (userByUser != null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_TELEXST);
            return resultModel;
        }
//        //判断手机号码是否3个月内修改
        if (user.getUpdateTelTime() != null && user.getUpdateTelTime().compareTo(DateUtils.DateToString(DateUtils.addMonth(new Date(), -3), "yyyy-MM-dd HH:mm:ss")) > 0) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.STORE_ERROR_CHANGEONE);
            return resultModel;
        }
        user.setUpdateTelTime("update");
        user.setTel(tel);
        user.setUsername(tel);
        user.setPromotionCode(StringUtils.getPromotionCode(user_type, tel));
        user = userService.save(user);
        if (user == null) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.USER_ERROR_SAVE);
            return resultModel;
        }
        sms.setStatus("1");
        sMSService.save(sms);
        return resultModel;
    }

    /**
     * 功能描述 密码修改需提供原密码验证
     *
     * @param pPwd       原密码
     * @param nPwd       新密码
     * @param rPwd       确认密码
     * @param session_id 用户id
     * @return
     */

    @RequestMapping("/api/updateNewPwd")
    @ResponseBody
    public ResultModel updateNewPwd(HttpServletRequest request) {
        String pPwd = request.getParameter("pPwd");
        String nPwd = request.getParameter("nPwd");
        String rPwd = request.getParameter("rPwd");
        String user_type = request.getParameter("user_type");
        String session_id = request.getParameter("session_id");
        User user = SessionUtils.getSubjectUser(session_id);
        if (false == user.getPwd().equals(pPwd)) {
            return getErr(ErrCode.USER_ERROR_PPWD);
        } else if (!nPwd.equals(rPwd)) {
            return getErr(ErrCode.USER_ERROR_PWS);
        }
        user.setPwd(rPwd);
        user.setUserType(user_type);
        user = userService.save(user);
        if (null == user) {
            return getErr(ErrCode.USER_ERROR_SAVE);
        }
        return getSucceed(ErrCode.SUCCEED);
    }

    /****
     * @功能: 更换某项用户信息
     * @作者: huyuangui create ver 1.0
     * @参数: session_id 主键
     * @参数: keys 要修改属性的字段名 按逗号分开
     * @参数: request keys 对应参数列表值
     */
    @RequestMapping("/api/user_changeUser")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel changeUser(HttpServletRequest request) {
        ResultModel resultModel = new ResultModel();
        String user_id = request.getParameter("session_id");
        String keys = request.getParameter("keys");
        if (StringUtils.isEmpty(keys)) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAMETER);
            return resultModel;
        }
        User user = new User();
        user.setSid(user_id);
        user = userService.findUserByUser(user);
        String[] arrayKey = keys.split(",");
        SuperRecordModel superRecordModel = this.getSRModel();
        String field = "";
        try {
            for (int i = 0; i < arrayKey.length; i++) {
                String value = superRecordModel.getString(arrayKey[i]);//request.getParameter(arrayKey[i]);
                field = arrayKey[i];
                Field f = User.class.getDeclaredField(field);
                f.setAccessible(true);
                if (f.getGenericType().toString().equals("class java.util.Date")) {
                    f.set(user, DateUtils.StringToDate(value));
                } else {
                    f.set(user, value);
                }
            }
        } catch (Exception e) {
            resultModel.setCode(0);
            resultModel.setMem(ErrCode.ERROR_PARAME_FIED + ":" + field);
            return resultModel;
        }
        userService.save(user);
        String session_id = (String) getValueFromSession(user.getSid());
        User user1 = JSON.parseObject(session_id, User.class);
        user.setSrmModel(user1.getSrmModel());
        resultModel.setData(JSON.toJSONString(user));
        return resultModel;
    }

    /*
    修改im用户信息
    * **/
    private boolean editIMUser(SuperRecordModel superRecordModel) {
        try {
            SuperRecordModel srm = new SuperRecordModel();
            String result = YunXinUtils.updateIMUser(superRecordModel, srm);
            Map parse = (Map) JSON.parse(result);
            int code = (int) parse.get("code");
            if (code == 200) {
                yunxinService.updateIMUser(srm);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /****
     * @功能: 修改用户名称 or 生日信息
     * @作者: gw create
     * @参数: sid 主键
     * @参数: birthday 生日日期(选填)
     * @参数: nickname 用户昵称(选填)
     */
    @RequestMapping("/api/change/birthday")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel changeUserBirthday() {
        SuperRecordModel SRModel = this.getSRModel();
        ResultModel resultModel = new ResultModel();
        try {
            SRModel.put("userId", SRModel.getString("session_id"));
            SRModel.put("sid", SRModel.getString("session_id"));
            SRModel.put("user_id", SRModel.getString("session_id"));
            userService.upUserBirthday(SRModel);
            User user = new User();
            user.setSid(SRModel.getString("session_id"));
            user = userService.findUserByUser(user);
            SuperRecordModel store = storeService.findStoreByUserId(SRModel);
            if (store != null) {
                SuperRecordModel srmModel = new SuperRecordModel();
                srmModel.put("store_id", store.getString("sid"));
                srmModel.put("address", store.getString("address"));
                srmModel.put("log", store.getString("log"));
                srmModel.put("lat", store.getString("lat"));
                user.setSrmModel(srmModel);
            }
            resultModel.setData(JSON.toJSONString(user));
            return resultModel;
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @模块: APP - 退出登录
     * @作者: gewei create ver 1.0
     * @说明: 销毁Redis用户信息的缓存
     * @参数: session_id 用户id(Key)
     */
    @RequestMapping("/api/login/off")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel loginOff(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getContextPath();
        try {
            String user_id = request.getParameter("session_id");
            SessionUtils.removeRedisByKey(user_id);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    /**
     * 获取地理位置
     */
    @RequestMapping("/api/user/getmap")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel getUserMap() {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            SRModel.put("user_id", SRModel.getString("session_id"));
            SRModel.put("userId", SRModel.getString("session_id"));
            SuperRecordModel srm = storeService.findStoreByUserId(SRModel);
            String log = srm.getString("log");
            if (!StringUtils.isEmpty(log)) {
                return getErr(ErrCode.ERROR_SYSTEM);
            }
            User user = userService.getUserMapBySid(SRModel);
            user.setPwd("");
            storeService.updateByUserId(SRModel);
            SuperRecordModel store = storeService.findStoreByUserId(SRModel);
            if (store != null) {
                SuperRecordModel srmModel = new SuperRecordModel();
                srmModel.put("store_id", store.getString("sid"));
                srmModel.put("address", store.getString("address"));
                srmModel.put("log", store.getString("log"));
                srmModel.put("lat", store.getString("lat"));
                user.setSrmModel(srmModel);
            }
            ResultModel resultModel = new ResultModel();
            resultModel.setData(JSON.toJSONString(user));
            return resultModel;
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 判断用户是否存在
     */
    @RequestMapping("/api/user/exist")
    @ResponseBody
    public ResultModel getUserExist() {
        SuperRecordModel SRModel = this.getSRModel();
        User user = new User();
        user.setTel(SRModel.getString("tel"));
        user.setUserType(SRModel.getString("ctype"));
        user = userService.login(user);
        if (user == null) {
            return getSucceed(0, ErrCode.SUCCEED);
        } else {
            return getSucceed(1, ErrCode.SUCCEED);
        }
    }


    /**
     * 判断用户是否存在
     */
    @RequestMapping("/api/user/info")
    @ResponseBody
    public ResultModel getUserInfo() {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            SRModel.put("user_id", SRModel.getString("session_id"));
            User user = userService.getUserMapBySid(SRModel);
            user.setPwd("");
            SuperRecordModel store = storeService.findStoreByUserId(SRModel);
            if (store != null) {
                SuperRecordModel srmModel = new SuperRecordModel();
                srmModel.put("store_id", store.getString("sid"));
                srmModel.put("address", store.getString("address"));
                srmModel.put("log", store.getString("log"));
                srmModel.put("lat", store.getString("lat"));
                user.setSrmModel(srmModel);
            }
            ResultModel resultModel = new ResultModel();
            resultModel.setData(JSON.toJSONString(user));
            return resultModel;
        } catch (Exception e) {
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * @return
     */
    @RequestMapping("/api/user/getname")
    @ResponseBody
    public ResultModel getUserName(HttpServletRequest request) {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            String ctype = request.getParameter("ctype");
            if (StringUtils.isEmpty(ctype)) {
                ctype = "popular";
            }
            User user = new User();
            user.setTel(SRModel.getString("tel"));
            user.setUserType(ctype);
            user = userService.login(user);
            if (user == null) {
                return getSucceed("");
            }
            SuperRecordModel userCouponBy = mCouponService.countUserCoupon(user.getSid());
            long vouchers = 0;
            if (userCouponBy != null) {
                vouchers = (Long) userCouponBy.get("coupon_count");
            }
            user.setVouchers(vouchers);
            return getSucceed(user, ErrCode.SUCCEED);
        } catch (Exception e) {
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /* 客户端修改
    *
    * session_id 登录id，nickname用户昵称  imgpath用户头像  sex用户性别0：女 1：男 2：未知
    * **/
    @RequestMapping("/api/user/pupolar_change")
    @ResponseBody
    @LoginAuth(isval = true)
    public ResultModel pupolarChange(HttpServletRequest request) {
        try {
            SuperRecordModel SRModel = this.getSRModel();
            String session_id = SRModel.getString("session_id");
            SRModel.put("sid", session_id);
            SuperRecordModel supers = new SuperRecordModel();
            supers.put("accid", session_id);
            if (SRModel.containsKey("sex")) {
                supers.put("gender", SRModel.getString("sex"));
            }
            if (SRModel.containsKey("imgpath")) {
                StringBuffer url = request.getRequestURL();
                String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
                supers.put("icon", tempContextUrl + SRModel.getString("imgpath"));
            }
            if (SRModel.containsKey("nickname")) {
                supers.put("name", SRModel.getString("nickname"));
            }
            editIMUser(supers);
            userService.updatePopular(SRModel);
            return getSucceed(ErrCode.SUCCEED);
        } catch (Exception e) {
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    /**
     * @功能: 用户钱包
     * @日期: liuwb by 2016-10-17 11:13:34 create
     * @参数: session_id 用户Id
     */
    @RequestMapping(value = "/api/user/wallet")
    @ResponseBody
    public ResultModel apiUserWallet() {
        SuperRecordModel srmParams = this.getSRModel();
        String session_id = srmParams.getString("session_id");
        srmParams.put("user_id", session_id);
        try {
            User user = userService.getUserMapBySid(srmParams);//用户信息
            SuperRecordModel store = storeService.findStoreByUserId(srmParams);//店铺信息
            if (user == null) {
                return getErr(ErrCode.USER_ERROR_NOEXIST);
            }
            SuperRecordModel wallet = new SuperRecordModel();
            wallet.put("userMoney", user.getRmoney());//资产余额
            //获取抵用券
            long userCoupon = getUserCoupon(session_id);

            //今日收入
            SuperRecordModel superRecordModel = new SuperRecordModel();
            superRecordModel.put("user_id", session_id);
            SuperRecordModel srm = mPaymentService.countDayPayMent(superRecordModel);
            double day_include = 0;
            if (srm != null && srm.get("day_include") != null) {
                day_include = ((BigDecimal) srm.get("day_include")).doubleValue();
            }
            wallet.put("userModou", user.getMagicBean());//魔豆(业务未定，暂且默认0)
            wallet.put("incomeDay", day_include);//今日收入(未规定具体业务表统计)
            wallet.put("settlement", 0);//未结算金额(未规定具体业务表统计)
            wallet.put("vouchers", userCoupon);//抵用卷(业务未定，暂且默认0)
            wallet.put("integral", 0);//积分(业务未定，暂且默认0)
            if (store != null && store.size() > 0) {
                wallet.put("store_id", store.getString("sid"));//店铺主键
                wallet.put("storename", store.getString("storename"));//店铺名称
                wallet.put("storeimg", store.getString("storeimg"));//店铺店铺头像
            }
            wallet.put("nickname", user.getNickname());//用户名称
            wallet.put("RedPacket", user.getRedPacket());//用户名称
            wallet.put("userId", user.getSid());//用户主键
            wallet.put("userTel", user.getUsername());//用户手机号
            wallet.put("unionId", user.getUnionId());//银联用户Id、如果为空
            return getSucceed(wallet);
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLog(e, "/api/user/wallet");
            return getErr(ErrCode.ERROR_SYSTEM);
        }

    }

    /**
     * 获取用户佣金
     */
    @RequestMapping(value = "/api/user/brokerage")
    @ResponseBody
    public ResultModel getUserBrokerage(HttpServletRequest request) {
        try {
            String user_id = request.getParameter("user_id");
            User userBySid = userService.getUserBySid(user_id);
            int counts = promotionService.countFromUserByHostId(user_id);
            Map<String, Object> map = new HashMap<String, Object>();
            String redPacket = userBySid.getRedPacket() + "";
            map.put("brokerage", redPacket);
            map.put("countPeople", counts);
            return getSucceed(map, ErrCode.SUCCEED);
        } catch (Exception e) {
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


    private User judgeOrderType(String orderType, String orderId) {
        User storeUser = new User();
        if (orderType.equals("user")) {
            SuperRecordModel service = new SuperRecordModel();
            service.put("orderno", orderId);
            service = fOrderServiceService.getStoreOrder(service);
            service.put("pushstatus", "1");//支付成功
            fOrderServiceService.updateStoreOrderStatus(service);
            SuperRecordModel store = storeService.getStoreBySid(service.get("store_id").toString());
            storeUser = userService.getUserBySid(store.get("user_id").toString());

        } else {
            MOrderPurchase out_trade_no = mOrderPurchaseService.findOneById(orderId);
            out_trade_no.setStatus(1);
            out_trade_no.setPrize(1);
            mOrderPurchaseService.updateOrderPurchase(out_trade_no);
            SuperRecordModel store = storeService.getStoreBySid(out_trade_no.getBuyStoreId());
            storeUser = userService.getUserBySid(store.get("user_id").toString());
        }
        return storeUser;
    }

    @RequestMapping(value = "/api/user/delete")
    @ResponseBody
    public ResultModel deleteUser(HttpServletRequest request) {
        String tel = request.getParameter("tel");
        String ctype = request.getParameter("ctype");
        User user = new User();
        user.setTel(tel);
        user.setUserType(ctype);
        User login = userService.login(user);
        if (login != null) {
            mBankListService.deleteMBankList(login.getSid());
            storeServieService.deleteServiceStoreUser(login.getSid());
            mgoodsService.deleteMGoodsDetail(login.getSid());
            mgoodsService.deleteMGoods(login.getSid());
            storeService.deleteMStore(login.getSid());
            userService.deleteUser(login.getSid());
            return getSucceed(ErrCode.SUCCEED);
        } else {
            return getErr(ErrCode.USER_ERROR_NOEXIST);
        }
    }

    @RequestMapping(value = "/api/user/userinfo")
    @ResponseBody
    public ResultModel getUserInfo(HttpServletRequest request) {
        String tel = request.getParameter("tel");
        String ctype = request.getParameter("ctype");
        User user = new User();
        user.setTel(tel);
        user.setUserType(ctype);
        User login = userService.login(user);
        return getSucceed(login, ErrCode.SUCCEED);
    }

    /**
     * 获取用户优惠券
     *
     * @param userid
     * @return
     */
    public long getUserCoupon(String userid) {
        SuperRecordModel userCouponBy = mCouponService.countUserCoupon(userid);
        long vouchers = 0;
        if (userCouponBy != null) {
            vouchers = (Long) userCouponBy.get("coupon_count");
        }
        return vouchers;
    }


    /**
     * 功能描述 设置支付密码
     *
     * @param
     * @return
     */

    @RequestMapping(value = "/api/user/updatePayPwd")
    @ResponseBody
    public ResultModel updatePayPwd(
            @ApiParam(name = "desPayPwd", value = "支付密码")
            @RequestParam(value = "desPayPwd") String desPayPwd,
            @ApiParam(name = "session_id", value = "用户ID")
            @RequestParam(value = "session_id") String dessession_id
    ) throws Exception {
        String session_id = Des3.decode(dessession_id);
        SuperRecordModel superRecordModel = new SuperRecordModel();
        superRecordModel.put("paypwd", desPayPwd);
        superRecordModel.put("sid", session_id);
        userService.updateUser(superRecordModel);
        payPassCodeService.deleteById(session_id);
        return getSucceed(ErrCode.SUCCEED);
    }

    /**
     * 功能描述 余额支付 by支付密码
     *
     * @param desPmoney      加密支付金额
     * @param coupon_id      优惠券id
     * @param desbrokerage   佣金
     * @param ctype          客户端类型
     * @param desOrderId     加密订单id
     * @param desPayPwd      加密支付密码
     * @param session_id     付款方id
     * @param seller_user_id 收款方id
     * @return
     */
    @RequestMapping(value = "/api/user/balancePay")
    @ResponseBody
    public ResultModel balancePay(
            @ApiParam(name = "desPmoney", value = "加密支付金额")
            @RequestParam(value = "desPmoney") String despmoney,
            @ApiParam(name = "coupon_id", value = "优惠券id")
            @RequestParam(value = "coupon_id", required = false) String coupon_id,
            @ApiParam(name = "sid", value = "优惠券sid")
            @RequestParam(value = "sid", required = false) String csid,
            @ApiParam(name = "desbrokerage", value = "佣金")
            @RequestParam(value = "desbrokerage") String desbrokerage,
            @ApiParam(name = "ctype", value = "客户端类型")
            @RequestParam(value = "ctype") String ctype,
            @ApiParam(name = "desOrderId", value = "加密订单id")
            @RequestParam(value = "desOrderId") String desOrderId,
            @ApiParam(name = "desPayPwd", value = "加密支付密码")
            @RequestParam(value = "desPayPwd") String desPayPwd,
            @ApiParam(name = "session_id", value = "付款方id")
            @RequestParam(value = "session_id") String session_id,
            @ApiParam(name = "seller_user_id", value = "收款方id")
            @RequestParam(value = "seller_user_id") String seller_user_id
    ) {
        User user = userService.getUserBySid(session_id);
        if (user == null) {
            logger.error("付款方信息错误");
            return getErr(ErrCode.ERROR_SYSTEM);
        }
        //des3 解密
        String spmoney = null;
        String orderId = null;
        String brokerage = null;
        try {
            spmoney = Des3.decode(despmoney);
            brokerage = Des3.decode(desbrokerage);
            orderId = Des3.decode(desOrderId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("参数异常");
            return getErr(ErrCode.ERROR_PARAMETER);
        }
        //订单号支付状态验证
        SuperRecordModel model = new SuperRecordModel();
        model.put("pay_status", 1);
        model.put("out_trade_no", orderId);
        MPayment prz = mPaymentService.findPaymentByOutTradeNoAndPayStatus(model);
        if (prz != null) {
            logger.info("订单号【" + orderId + "】重复付款");
            return getErr(ErrCode.ERROR_PAY);
        }

        //余额验证
        Double pmoney = Double.valueOf(spmoney);
        if (user.getRmoney() < pmoney) {
            return getErr(ErrCode.BANK_ERROR_MONEY_FORMAT);
        }
        //验证当天密码锁定状态
        SPayPassCode payPassCode = payPassCodeService.getPayPassCode(user.getSid());
        //记录为空
        if (payPassCode != null && payPassCode.getErrCount() == 3) {
            if (new Date().getTime() < payPassCode.getOpenTime().getTime()) {
                return getErr(ErrCode.BANK_ERROR_24_CLOSE);
            }
            if (new Date().getTime() > payPassCode.getOpenTime().getTime()) {
                payPassCode.setStatus(0);
                payPassCode.setErrCount(0);
                payPassCode.setCloseTime(null);
                payPassCode.setOpenTime(null);
                payPassCodeService.update(payPassCode);
                //  payPassCodeService.deleteById(user.getSid());
            }
        }
        if (!desPayPwd.equals(user.getPaypwd())) {
            SPayPassCode pre = payPassCodeService.getPayPassCode(user.getSid());
            if (pre == null) {
                SPayPassCode sPayPassCode = new SPayPassCode();
                sPayPassCode.setUserId(user.getSid());
                sPayPassCode.setErrCount(1);
                sPayPassCode.setStatus(0);
                sPayPassCode.setCloseTime(new Date());
                sPayPassCode.setOpenTime(DateUtil.hour(new Date(), 3));
                sPayPassCode.setcTime(new Date());
                payPassCodeService.insert(sPayPassCode);
                return getErr("密码错误您还有2次机会");
            } else if (pre.getErrCount() < 3) {
                pre.setErrCount(pre.getErrCount() + 1);
                pre.setStatus(0);
                pre.setCloseTime(new Date());
                pre.setOpenTime(DateUtil.hour(new Date(), 3));
                payPassCodeService.update(pre);
                return getErr(MessageFormat.format("密码错误您还有{0}次机会", 3 - pre.getErrCount()));
            } else if (pre.getErrCount() >= 3) {
                return getErr(ErrCode.BANK_ERROR_24_CLOSE);
            }
        }
        String payType = "Service";
        //订单验证
        BigDecimal orderMoney;
        String content = "";
        if (switchClientTypeByOrderId(orderId).equals("user")) {
            SuperRecordModel order = orderServiceService.getStoreOrderByOrderNo(orderId);
            if (order == null) {
                logger.error("订单未找到");
                return getErr(ErrCode.ERROR_ORDER_DETAIL_INFO);
            }
            BigDecimal moneys = (BigDecimal) order.get("money");
            orderMoney = moneys;
        } else if (switchClientTypeByOrderId(orderId).equals("business")) {
            MOrderPurchase order = mOrderPurchaseService.findOneByOrderId(orderId);
            if (order == null) {
                logger.error("订单未找到");
                return getErr(ErrCode.ERROR_ORDER_DETAIL_INFO);
            }
            orderMoney = BigDecimal.valueOf(order.getMoney());
        } else if (switchClientTypeByOrderId(orderId).equals("Ho")) {
            MGPOrder mgpOrder = mgpOrderService.findOneBySid(orderId);
            if (mgpOrder == null) {
                logger.error("订单未找到");
                return getErr(ErrCode.ERROR_ORDER_DETAIL_INFO);
            }
            payType = "TRANSFER";
            content = mgpOrder.getContent();
            orderMoney = BigDecimal.valueOf(mgpOrder.getMoney());
        } else {
            logger.error("订单未找到");
            return getErr(ErrCode.ERROR_SYSTEM);
        }
        SuperRecordModel superRecordModel = new SuperRecordModel();

        superRecordModel.put("orderId", orderId);
        superRecordModel.put("seller_user_id", seller_user_id);
        superRecordModel.put("coupon_id", coupon_id);
        superRecordModel.put("pmoney", pmoney);
        superRecordModel.put("brokerage", brokerage);
        superRecordModel.put("orderMoney", orderMoney);
        superRecordModel.put("payType", payType);
        superRecordModel.put("content", content);
        superRecordModel.put("csid", csid);
        try {
            userService.balanceHandle(user, superRecordModel);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("余额交易出错", e);
            ErrorLog(e, "/api/user/balancePay", "userService.balanceHandle");
            return getErr("余额交易出错");
        }
        return getSucceed(ErrCode.SUCCEED);
    }

    //商家入驻列表 Merchants settled list

    @RequestMapping("/api/user_enterStoresList")
    @ResponseBody
    public ResultModel enterStoresList(HttpServletRequest request, HttpServletResponse response) throws IOException, WriteException {
        //店铺名称
        String storename = request.getParameter("");
        //手机号
        String tel = request.getParameter("tel");
        //省份
        String province = request.getParameter("province");
        //市
        String city = request.getParameter("city");
        //区/县
        String area = request.getParameter("area");
        //开店时间开始时间
        String starttime = request.getParameter("starttime");
        //开店时间开始时间
        String endtime = request.getParameter("endtime");
        // 显示记录的一页几行
        String row = request.getParameter("row");
        // 显示记录的页数
        String page = request.getParameter("page");

        //是否导出
        String export = request.getParameter("export");

        SuperRecordModel srm = new SuperRecordModel();
        srm.put("storename", storename);
        srm.put("tel", tel);
        srm.put("province", province);
        srm.put("city", city);
        srm.put("area", area);
        srm.put("starttime", starttime);
        srm.put("endtime", endtime);
        int ipage = Integer.parseInt(page);
        int irow = Integer.parseInt(row);
        if (ipage < 1) {
            ipage = 1;
        }
        srm.put("page", ipage);
        if (irow < 1) {
            irow = 1;
        }
        srm.put("row", irow);
        int offset = (ipage - 1) * irow;
        srm.put("offset", offset);
        if (StringUtils.isEmpty(export)) {
            Map map = new HashMap<>();
            Long count = userService.findEnterStoresListByMapCount(srm);
            List<SuperRecordModel> models = userService.findEnterStoresListByMap(srm);
            map.put("count", count);
            map.put("models", models);
            return getSucceed(map, ErrCode.SUCCEED);
        } else {

            List<SuperRecordModel> models = userService.findEnterStoresListExportByMap(srm);
            String title[] = {"开店时间", "店铺名称", "真实姓名", "手机号码", "店铺地址", "账单余额", "剩余推广金"};
            List<List> lists = new ArrayList<List>();
            for (SuperRecordModel po : models) {
                List<String> cusList = new ArrayList<>();
                cusList.add(po.getString("addtime"));
                cusList.add(po.getString("storename"));
                cusList.add(po.getString("realname"));
                cusList.add(po.getString("tel1"));
                cusList.add(po.getString("address"));
                String rmoney = ((BigDecimal) po.get("rmoney")).doubleValue() + "";
                cusList.add(rmoney);
                String red_packet = ((BigDecimal) po.get("red_packet")).doubleValue() + "";
                cusList.add(red_packet);
                lists.add(cusList);
            }
            response.reset();
            response.setContentType("octets/stream");
            String fileName = "入住商家列表.xls";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            OutputStream outputStream = response.getOutputStream();
            StringUtils.writeExcel(outputStream, title, lists, "商家列表");
            return getSucceed("");
        }
    }

    //商家入驻列表详情 Merchants settled Detail list
    @RequestMapping("/api/user_enterStoresDetailList")
    @ResponseBody
    public ResultModel enterStoresDetailList(HttpServletRequest request) {
        //用户sid
        String sid = request.getParameter("sid");
        SuperRecordModel srm = new SuperRecordModel();
        srm.put("sid", sid);
        SuperRecordModel models = userService.findEnterStoresListDetailByMap(srm);
        int count = promotionService.countFromUserByHostId(sid);
        models.put("countPeople", count);
        return getSucceed(models, ErrCode.SUCCEED);
    }

    //入驻商家导出
    @RequestMapping("/api/user_enterStoresExportList")
    @ResponseBody
    public ResultModel enterStoresExportList(HttpServletRequest request) {
        //店铺名称
        String storename = request.getParameter("storename");
        //手机号
        String tel = request.getParameter("tel");
        //省份
        String province = request.getParameter("province");
        //市
        String city = request.getParameter("city");
        //区/县
        String area = request.getParameter("area");
        //开店时间开始时间
        String starttime = request.getParameter("starttime");
        //开店时间开始时间
        String endtime = request.getParameter("endtime");
        // 显示记录的一页几行

        SuperRecordModel srm = new SuperRecordModel();
        srm.put("storename", storename);
        srm.put("tel", tel);
        srm.put("province", province);
        srm.put("city", city);
        srm.put("area", area);
        srm.put("starttime", starttime);
        srm.put("endtime", endtime);
        List<SuperRecordModel> models = userService.findEnterStoresListByMap(srm);
        return getSucceed(models, ErrCode.SUCCEED);
    }

    /**
     * 判断订单类型
     *
     * @param OrderId
     * @return
     */
    public String switchClientTypeByOrderId(String OrderId) {
        String str = OrderId.substring(0, 2);
        String clientType;
        switch (str) {
            case "SO":
                clientType = "user";
                break;
            case "Co":
                clientType = "business";
                break;
            case "Ho":
                clientType = "Ho";
                break;
            default:
                clientType = "other";
        }
        return clientType;
    }

}